<template>
  <div class="users">
    <div class="title">角色管理</div>
    <div class="operation-box">
      <el-button type="success" :icon="Plus" @click="before_add"
        >新增</el-button
      >
      <el-button type="primary" :icon="Refresh" @click="table_reload"
        >刷新</el-button
      >

      <el-input
        v-model="search_username"
        class="w-50 m-2"
        size="default"
        style="width: 180px; margin: 0 10px 0 30px"
        clearable
        :prefix-icon="Search"
        @input="search_filter"
        placeholder="输入用户昵称搜索"
      />
      <el-input
        v-model="search_phone"
        class="w-50 m-2"
        size="default"
        :prefix-icon="Search"
        style="width: 180px; margin: 0 10px 0 0px"
        clearable
        @input="search_filter"
        placeholder="输入用户手机号搜索"
      />
      <el-button type="default" @click="search_reset">重置</el-button>
    </div>

    <el-table
      :data="table_data"
      table-layout="auto"
      size="large"
      style="width: 100%"
      height="550"
      v-loading="table_loading"
      :element-loading-svg="table_svg"
      class="custom-loading-svg"
      element-loading-svg-view-box="-10, -10, 50, 50"
      :row-class-name="tableRowClassName"
    >
      <el-table-column label="创建时间" prop="date" />
      <el-table-column label="账号" prop="account" />
      <el-table-column label="昵称" prop="user_name" />
      <el-table-column label="手机号" prop="phone" />
      <el-table-column label="地址" prop="address" />
      <el-table-column align="right">
        <template #default="scope">
          <el-button
            size="default"
            type="default"
            @click="before_permit_menu_confirm(scope.$index, scope.row)"
            >分配菜单权限</el-button
          >
          <el-button
            size="default"
            type="primary"
            @click="before_handle_edit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="是否确定删除"
            @confirm="handle_delete(scope.$index, scope.row)"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button size="default" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑&新增 角色信息窗口 -->
    <el-drawer v-model="show_info" :direction="direction">
      <template #header>
        <h4 style="text-align: left">
          {{
            show_info == "edit"
              ? "编辑信息"
              : show_info == "new"
              ? "添加管理员"
              : ""
          }}
        </h4>
      </template>
      <template #default>
        <div>
          <el-form
            label-position="left"
            label-width="100px"
            v-if="show_info == 'edit'"
            :model="edit_info"
            style="max-width: 460px"
          >
            <el-form-item label="账号名称">
              <el-input
                placeholder="请输入账号名称"
                disabled
                maxlength="10"
                show-word-limit
                v-model="edit_info.account"
              />
            </el-form-item>
            <el-form-item label="密码">
              <el-input
                placeholder="请输入密码"
                clearable
                maxlength="20"
                show-word-limit
                v-model="edit_info.password"
              />
            </el-form-item>
            <el-form-item label="昵称">
              <el-input
                placeholder="请输入用户昵称"
                clearable
                maxlength="10"
                show-word-limit
                v-model="edit_info.user_name"
              />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input
                clearable
                placeholder="请输入手机号"
                maxlength="11"
                show-word-limit
                v-model="edit_info.phone"
              />
            </el-form-item>
            <el-form-item label="地址">
              <el-input
                placeholder="请输入地址"
                clearable
                type="textarea"
                v-model="edit_info.address"
              />
            </el-form-item>
          </el-form>

          <el-form
            label-position="left"
            label-width="100px"
            v-if="show_info == 'new'"
            :model="new_info"
            style="max-width: 460px"
          >
            <el-form-item label="账号名称">
              <el-input
                placeholder="请输入账号名称"
                clearable
                maxlength="20"
                show-word-limit
                v-model="new_info.account"
              />
            </el-form-item>
            <el-form-item label="密码">
              <el-input
                placeholder="请输入密码"
                clearable
                maxlength="20"
                show-word-limit
                v-model="new_info.password"
              />
            </el-form-item>
            <el-form-item label="昵称">
              <el-input
                placeholder="请输入用户昵称"
                clearable
                maxlength="10"
                show-word-limit
                v-model="new_info.user_name"
              />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input
                clearable
                placeholder="请输入手机号"
                maxlength="11"
                show-word-limit
                v-model="new_info.phone"
              />
            </el-form-item>
            <el-form-item label="地址">
              <el-input
                placeholder="请输入地址"
                clearable
                type="textarea"
                v-model="new_info.address"
              />
            </el-form-item>
            <el-form-item label="超级管理员">
              <el-switch
                v-model="new_info.permit_super"
                class="ml-2"
                :active-value="1"
                :inactive-value="0"
                inline-prompt
                size="default"
                style="--el-switch-on-color: #13ce66"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="show_info = false">取消</el-button>
          <el-button
            type="primary"
            @click="handle_edit"
            v-loading.fullscreen.lock="global_loading"
            >提交</el-button
          >
        </div>
      </template>
    </el-drawer>

    <!-- 分配菜单窗口 -->
    <el-dialog
      v-model="permit_window_visible"
      style="text-align: left"
      title="分配菜单"
    >
      <el-transfer
        filterable
        filter-placeholder="输入名称搜索"
        v-model="permit_menu_option_list_yes"
        :titles="['未分配项', '已分配项']"
        :data="permit_menu_option_list_no"
        style="text-align: center"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permit_window_visible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="permit_menu_confirm_loading"
            @click="permit_menu_confirm"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, reactive } from "vue";
import { Plus, Refresh, InfoFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { get_menu_list } from "../../../common/data";
import { useStore } from "vuex";

import { getUserList, userAdd, userEdit, userDelete} from "../../ajaxServices/user";

interface User {
  id: number;
  date: string;
  account: string;
  phone: string;
  address: string;
  permit_super: number;
  password: string;
}

interface permitMenu {
  key: number;
  value: string;
  label: string;
  disabled: boolean;
}

const store = useStore();
const search = ref("");
const table_loading = ref(false);
const global_loading = ref(false);
const show_info = ref(false); // 展开新增编辑管理员信息弹窗
const edit_info = ref(null); // 表单编辑信息
const permit_window_visible = ref(false); // 展开分配菜单弹窗
const permit_menu_confirm_loading = ref(false); // 分配菜单确认按钮loading
const new_info = ref({
  id: 0,
  account: "",
  user_name: "",
  phone: "",
  address: "",
  permit_super: 0,
  password: "",
});
const table_svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `;

const table_data_origin = ref<User>([]);
const table_data = ref<User>(table_data_origin.value || []);
const search_username = ref("");
const search_phone = ref("");

// 输入框搜索
const search_filter = () => {
  if (search_username.value == "" && search_phone.value == "") {
    table_data.value = table_data_origin.value;
    return;
  }

  if (search_username.value != "" && search_phone.value == "") {
    table_data.value = table_data_origin.value.filter((data: any) =>
      data.user_name.toLowerCase().includes(search_username.value.toLowerCase())
    );
  }

  if (search_username.value == "" && search_phone.value != "") {
    table_data.value = table_data_origin.value.filter((data: any) =>
      data.phone.toLowerCase().includes(search_phone.value.toLowerCase())
    );
  }

  if (search_username.value != "" && search_phone.value != "") {
    table_data.value = table_data_origin.value.filter(
      (data: any) =>
        data.phone.toLowerCase().includes(search_phone.value.toLowerCase()) &&
        data.user_name
          .toLowerCase()
          .includes(search_username.value.toLowerCase())
    );
  }
};

// 重置搜索框
const search_reset = () => {
  search_username.value = "";
  search_phone.value = "";
  table_data.value = table_data_origin.value;
};

const before_add = () => {
  new_info.value = {
    id: 0,
    account: "",
    user_name: "",
    phone: "",
    address: "",
    permit_super: 0,
    password: "",
  };
  show_info.value = "new";
};

// 打开编辑信息窗口
const before_handle_edit = (index: number, row: User) => {
  edit_info.value = row;

  show_info.value = "edit";
  console.log(index, row);
};
// 编辑提交
const handle_edit = () => {
  // 编辑修改
  if (show_info.value == "edit") {
    //if (!edit_info.value.id || edit_info.value.id == "") {
      //ElMessage({ message: "未获取到用户id", type: "warning" });
      //return;
    //}
    if (!edit_info.value.account || edit_info.value.account == "") {
      ElMessage({ message: "账号不能为空", type: "warning" });
      return;
    }

    if (!edit_info.value.password || edit_info.value.password == "") {
      ElMessage({ message: "密码不能为空", type: "warning" });
      return;
    }

    if (!edit_info.value.phone || edit_info.value.phone == "") {
      ElMessage({ message: "手机号不能为空", type: "warning" });
      return;
    }

    global_loading.value = true;

    let reqData = {
      id: edit_info.value.id,
      account: edit_info.value.account || "",
      password: edit_info.value.password || "",
      phone: edit_info.value.phone || "",
      permit_super: edit_info.value.permit_super || 0,
      user_name: edit_info.value.user_name || "",
      address: edit_info.value.address || "",
    };
    userEdit(reqData)
      .then((res: any) => {
        global_loading.value = false;
        show_info.value = false;
        ElMessage({
          message: "修改成功",
          type: "success",
        });
        // 重新加载表单数据
        table_reload();
      })
      .catch(() => {
        global_loading.value = false;
      });
    return;
  }

  // 新增
  if (show_info.value == "new") {
    if (!new_info.value.account || new_info.value.account == "") {
      ElMessage({ message: "账号不能为空", type: "warning" });
      return;
    }

    if (!new_info.value.password || new_info.value.password == "") {
      ElMessage({ message: "密码不能为空", type: "warning" });
      return;
    }

    if (!new_info.value.phone || new_info.value.phone == "") {
      ElMessage({ message: "手机号不能为空", type: "warning" });
      return;
    }

    global_loading.value = true;

    let reqData = {
      account: new_info.value.account || "",
      password: new_info.value.password || "",
      phone: new_info.value.phone || "",
      permit_super: new_info.value.permit_super || 0,
      user_name: new_info.value.user_name || "",
      address: new_info.value.address || "",
    };
    userAdd(reqData)
      .then((res: any) => {
        console.log("################## AddUser ################");
        console.log(res);
        global_loading.value = false;
        show_info.value = false;
        ElMessage({
          message: "添加成功",
          type: "success",
        });
        // 重新加载表单数据
        table_reload();
      })
      .catch(() => {
        global_loading.value = false;
      });
  }
};
// 删除
const handle_delete = (index: number, row: any) => {
  if (!row.id || row.id == "") {
    ElMessage({ message: "手机号不能为空", type: "warning" });
    return;
  }
  table_loading.value = true;
  userDelete({ id: row.id || "" })
    .then((res: any) => {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      // 重新加载表单数据
      table_reload();
    })
    .catch(() => {
      table_loading.value = false;
    });
};
// 分配菜单
const before_permit_menu_confirm = (index: number, row: User) => {
  edit_info.value = row;
  permit_window_visible.value = true;
};

// 分配菜单提交保存
const permit_menu_confirm = () => {
  const permit_menu = [];
  if (permit_menu_option_list_yes.value.length <= 0) {
    permit_window_visible.value = false;
    return;
  }

  for (let index of permit_menu_option_list_yes.value) {
    permit_menu.push(get_menu_list()[index].value);
  }

  permit_menu_confirm_loading.value = true;
  setTimeout(() => {
    permit_menu_confirm_loading.value = false;
    permit_window_visible.value = false;
    ElMessage({
      message: `用户${edit_info.value.account}权限设置成功`,
      type: "success",
    });
  }, 3000);

  console.log(permit_menu);
};

// 查询所有管理员
const table_reload = () => {
  table_loading.value = true;

  getUserList({}).then((res: any) => {
    table_loading.value = false;
    table_data_origin.value = res.data || [];
    table_data.value = res.data || [];
  });
};

// 初始化菜单权限
const generateData = () => {
  const menu_list = get_menu_list();
  const data: permitMenu[] = [];
  menu_list.map((item: any, index: number) => {
    item.value != "0" &&
      item.value != "1-0" &&
      data.push({
        key: index,
        label: item.label,
        value: item.value,
        disabled: false,
      });
  });

  return data;
};
const permit_menu_option_list_no = ref<permitMenu[]>(generateData());
const permit_menu_option_list_yes = ref([]);

// 高亮自己
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User;
  rowIndex: number;
}) => {
  let user_id = store.state.user_info && store.state.user_info.id;
  if (row.id == user_id) {
    return "success-row";
  }

  return "";
};

table_reload();
</script>

<style scoped lang="scss">
.users {
  width: 95%;
  height: 80%;
  border: 1px solid #eee;
  border-radius: 5px;
  margin: auto;
  box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.12);

  .title {
    width: 100%;
    height: 55px;
    font-size: 18px;
    color: #000;
    text-align: left;
    line-height: 55px;
    text-indent: 20px;
    border-bottom: 1px solid #eee;
  }

  .operation-box {
    width: 100%;
    height: 70px;
    display: flex;
    align-items: center;
    padding-left: 20px;
  }
}
</style>

<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: #fafcff;
}
</style>
